<template>
  <div class="messages-page">
    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="bg-white dark:bg-gray-900 rounded-xl shadow-sm">
        <!-- 导航栏容器 -->
        <div class="px-6 pt-6">
          <!-- 小标签 -->
          <div
            class="text-sm text-gray-900 dark:text-gray-100 font-medium mb-4"
          >
            消息中心
          </div>

          <!-- 消息类型切换和操作按钮 -->
          <div class="flex items-center justify-between">
            <el-tabs v-model="activeTab" class="messages-tabs flex-1">
              <el-tab-pane name="all">
                <template #label>
                  <div class="flex items-center space-x-2">
                    <el-icon><Message /></el-icon>
                    <span>全部消息</span>
                    <el-badge
                      v-if="totalUnread"
                      :value="totalUnread"
                      class="ml-2"
                    />
                  </div>
                </template>
              </el-tab-pane>

              <el-tab-pane name="system">
                <template #label>
                  <div class="flex items-center space-x-2">
                    <el-icon><Bell /></el-icon>
                    <span>系统通知</span>
                    <el-badge
                      v-if="unreadSystemCount"
                      :value="unreadSystemCount"
                      class="ml-2"
                    />
                  </div>
                </template>
              </el-tab-pane>

              <el-tab-pane name="interaction">
                <template #label>
                  <div class="flex items-center space-x-2">
                    <el-icon><ChatDotRound /></el-icon>
                    <span>互动消息</span>
                    <el-badge
                      v-if="unreadInteractionCount"
                      :value="unreadInteractionCount"
                      class="ml-2"
                    />
                  </div>
                </template>
              </el-tab-pane>

              <el-tab-pane name="activity">
                <template #label>
                  <div class="flex items-center space-x-2">
                    <el-icon><Present /></el-icon>
                    <span>活动通知</span>
                    <el-badge
                      v-if="unreadActivityCount"
                      :value="unreadActivityCount"
                      class="ml-2"
                    />
                  </div>
                </template>
              </el-tab-pane>
            </el-tabs>

            <!-- 操作按钮 -->
            <div class="flex items-center space-x-4">
              <el-button type="primary" @click="markAllRead">
                全部标记为已读
              </el-button>
              <el-button @click="clearAllMessages"> 清空所有消息 </el-button>
            </div>
          </div>
        </div>

        <!-- 筛选和操作栏 -->
        <div class="px-6 py-4 border-b border-gray-100 dark:border-gray-800">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <div class="filter-select">
                <el-select
                  v-model="timeFilter"
                  placeholder="时间筛选"
                  class="!w-40"
                >
                  <el-option label="全部时间" value="all" />
                  <el-option label="最近一周" value="week" />
                  <el-option label="最近一月" value="month" />
                  <el-option label="最近三月" value="three_months" />
                </el-select>
              </div>
              <div class="filter-select">
                <el-select
                  v-model="statusFilter"
                  placeholder="状态筛选"
                  class="!w-40"
                >
                  <el-option label="全部状态" value="all" />
                  <el-option label="未读" value="unread" />
                  <el-option label="已读" value="read" />
                </el-select>
              </div>
              <div class="search-input">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索消息内容"
                  class="!w-80"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
            <div class="flex items-center space-x-4">
              <el-button type="primary" text @click="refreshMessages">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-dropdown trigger="click" @command="handleBatchCommand">
                <el-button>
                  批量操作
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="markRead"
                      >标记已读</el-dropdown-item
                    >
                    <el-dropdown-item command="delete" divided
                      >删除选中</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="messages-list">
          <el-table
            v-model:selected="selectedMessages"
            :data="filteredMessages"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column width="80">
              <template #default="{ row }">
                <div class="flex justify-center">
                  <div
                    class="w-2 h-2 rounded-full"
                    :class="
                      row.isRead
                        ? 'bg-gray-300'
                        : 'bg-primary-500 animate-pulse'
                    "
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="消息内容" min-width="300">
              <template #default="{ row }">
                <div class="flex items-start space-x-3 py-2">
                  <el-avatar :size="40" :src="row.avatar">
                    <img src="/default-avatar.png" alt="头像" />
                  </el-avatar>
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center space-x-2">
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ row.title }}
                      </span>
                      <el-tag
                        size="small"
                        :type="getTagType(row.type)"
                        class="ml-2"
                      >
                        {{ getTypeLabel(row.type) }}
                      </el-tag>
                    </div>
                    <p
                      class="text-gray-600 dark:text-gray-400 mt-1 text-sm line-clamp-2"
                    >
                      {{ row.content }}
                    </p>
                    <div class="mt-2" v-if="row.actions?.length">
                      <el-button
                        v-for="action in row.actions"
                        :key="action.key"
                        type="primary"
                        link
                        size="small"
                        @click="handleMessageAction(row, action)"
                      >
                        {{ action.text }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="时间" width="180">
              <template #default="{ row }">
                <div class="text-gray-500 dark:text-gray-400 text-sm">
                  {{ formatTime(row.time) }}
                </div>
                <div class="text-gray-400 dark:text-gray-500 text-xs mt-1">
                  {{ formatDetailTime(row.time) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="!row.isRead"
                  type="primary"
                  link
                  size="small"
                  @click="markMessageRead(row.id)"
                >
                  标记已读
                </el-button>
                <el-popconfirm
                  title="确定要删除这条消息吗？"
                  @confirm="deleteMessage(row.id)"
                >
                  <template #reference>
                    <el-button type="danger" link size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty v-if="filteredMessages.length === 0" description="暂无消息">
            <template #image>
              <el-icon :size="60" class="text-gray-400"><Message /></el-icon>
            </template>
          </el-empty>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Bell,
  ChatDotRound,
  Present,
  Message,
  Search,
  Refresh,
  ArrowDown,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const route = useRoute();
const router = useRouter();

// 状态管理
const activeTab = ref(route.query.tab || "all");
const timeFilter = ref("all");
const statusFilter = ref("all");
const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const selectedMessages = ref([]);

// 消息数据（模拟数据）
const messages = ref([
  {
    id: 1,
    type: "system",
    title: "系统升级通知",
    content: "系统将于今晚22:00-23:00进行例行维护升级，请提前安排您的操作。",
    time: "2024-03-15 10:00:00",
    isRead: false,
    avatar: "/system-avatar.png",
    actions: [{ key: "detail", text: "查看详情" }],
  },
  {
    id: 2,
    type: "interaction",
    title: "新的评论回复",
    content: '用户"快乐旅行者"回复了您的评论：景区确实很美，下次一起去玩啊！',
    time: "2024-03-14 15:30:00",
    isRead: true,
    avatar: "/default-avatar.png",
    sourceType: "scenic",
    sourceId: "123",
    commentId: "456",
    actions: [
      { key: "reply", text: "回复" },
      { key: "view", text: "查看原文" },
    ],
  },
  {
    id: 3,
    type: "activity",
    title: "限时优惠活动",
    content: "端午节期间，景区门票全场8折，还有更多优惠等着您！",
    time: "2024-03-13 09:00:00",
    isRead: false,
    avatar: "/activity-avatar.png",
    eventId: "123",
    actions: [{ key: "view", text: "查看活动" }],
  },
]);

// 计算属性
const filteredMessages = computed(() => {
  let result = [...messages.value];

  // 标签过滤
  if (activeTab.value !== "all") {
    result = result.filter((msg) => msg.type === activeTab.value);
  }

  // 时间过滤
  if (timeFilter.value !== "all") {
    const now = dayjs();
    const timeRanges = {
      week: now.subtract(1, "week"),
      month: now.subtract(1, "month"),
      three_months: now.subtract(3, "month"),
    };
    result = result.filter((msg) =>
      dayjs(msg.time).isAfter(timeRanges[timeFilter.value]),
    );
  }

  // 状态过滤
  if (statusFilter.value !== "all") {
    result = result.filter((msg) =>
      statusFilter.value === "read" ? msg.isRead : !msg.isRead,
    );
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
      (msg) =>
        msg.title.toLowerCase().includes(keyword) ||
        msg.content.toLowerCase().includes(keyword),
    );
  }

  return result;
});

// 未读消息计数
const unreadSystemCount = computed(
  () =>
    messages.value.filter((msg) => msg.type === "system" && !msg.isRead).length,
);

const unreadInteractionCount = computed(
  () =>
    messages.value.filter((msg) => msg.type === "interaction" && !msg.isRead)
      .length,
);

const unreadActivityCount = computed(
  () =>
    messages.value.filter((msg) => msg.type === "activity" && !msg.isRead)
      .length,
);

const totalUnread = computed(
  () => messages.value.filter((msg) => !msg.isRead).length,
);

// 工具函数
const getTypeLabel = (type) => {
  const typeMap = {
    system: "系统通知",
    interaction: "互动消息",
    activity: "活动通知",
  };
  return typeMap[type] || type;
};

const getTagType = (type) => {
  const typeMap = {
    system: "info",
    interaction: "success",
    activity: "warning",
  };
  return typeMap[type] || "info";
};

const formatTime = (time) => {
  return dayjs(time).fromNow();
};

const formatDetailTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 事件处理
const handleSelectionChange = (val) => {
  selectedMessages.value = val;
};

const handleBatchCommand = async (command) => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning("请先选择消息");
    return;
  }

  if (command === "markRead") {
    await markMessagesRead(selectedMessages.value.map((msg) => msg.id));
  } else if (command === "delete") {
    await deleteMessages(selectedMessages.value.map((msg) => msg.id));
  }
};

const markMessageRead = async (id) => {
  try {
    // TODO: 调用后端 API 标记消息已读
    const message = messages.value.find((msg) => msg.id === id);
    if (message) {
      message.isRead = true;
      ElMessage.success("已标记为已读");
    }
  } catch (error) {
    console.error("标记消息已读失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

const markMessagesRead = async (ids) => {
  try {
    // TODO: 调用后端 API 批量标记消息已读
    messages.value.forEach((msg) => {
      if (ids.includes(msg.id)) {
        msg.isRead = true;
      }
    });
    ElMessage.success("已标记选中消息为已读");
  } catch (error) {
    console.error("批量标记消息已读失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

const deleteMessage = async (id) => {
  try {
    // TODO: 调用后端 API 删除消息
    messages.value = messages.value.filter((msg) => msg.id !== id);
    ElMessage.success("删除成功");
  } catch (error) {
    console.error("删除消息失败:", error);
    ElMessage.error("删除失败，请重试");
  }
};

const deleteMessages = async (ids) => {
  try {
    await ElMessageBox.confirm("确定要删除选中的消息吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // TODO: 调用后端 API 批量删除消息
    messages.value = messages.value.filter((msg) => !ids.includes(msg.id));
    ElMessage.success("批量删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除消息失败:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

const markAllRead = async () => {
  try {
    await ElMessageBox.confirm("确定要将所有消息标记为已读吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    });

    // TODO: 调用后端 API 标记所有消息已读
    messages.value.forEach((msg) => (msg.isRead = true));
    ElMessage.success("已将所有消息标记为已读");
  } catch (error) {
    if (error !== "cancel") {
      console.error("标记所有消息已读失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  }
};

const clearAllMessages = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清空所有消息吗？此操作不可恢复！",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // TODO: 调用后端 API 清空所有消息
    messages.value = [];
    ElMessage.success("已清空所有消息");
  } catch (error) {
    if (error !== "cancel") {
      console.error("清空消息失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  }
};

const refreshMessages = async () => {
  try {
    // TODO: 调用后端 API 刷新消息列表
    ElMessage.success("刷新成功");
  } catch (error) {
    console.error("刷新消息列表失败:", error);
    ElMessage.error("刷新失败，请重试");
  }
};

const handleMessageAction = (message, action) => {
  switch (action.key) {
    case "reply":
      // TODO: 实现回复功能
      break;
    case "view":
      if (message.type === "activity") {
        // 跳转到活动详情页
        router.push({
          path: `/community/event/${message.eventId}`,
          query: { from: "messages" },
        });
      } else if (message.type === "interaction") {
        // 根据来源类型跳转到对应页面
        let path = "";
        switch (message.sourceType) {
          case "scenic":
            path = `/scenic/${message.sourceId}`;
            break;
          case "article":
            path = `/community/article/${message.sourceId}`;
            break;
          case "community":
            path = `/community/post/${message.sourceId}`;
            break;
          case "photography":
            path = `/photography/${message.sourceId}`;
            break;
          default:
            ElMessage.warning("暂不支持查看该类型的原文");
            return;
        }
        // 跳转到对应页面并定位到评论
        router.push({
          path,
          query: {
            from: "messages",
            comment_id: message.commentId, // 用于页面加载后定位到具体评论
          },
        });
      }
      break;
    case "buy":
      router.push("/shop/tickets");
      break;
    case "share":
      // TODO: 实现分享功能
      break;
    case "detail":
      // 跳转到系统通知详情页
      router.push({
        path: "/user/notification",
        query: { id: message.id },
      });
      break;
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  // TODO: 重新加载数据
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  // TODO: 重新加载数据
};

// 监听路由参数变化
watch(
  () => route.query.tab,
  (newTab) => {
    if (newTab) {
      activeTab.value = newTab;
    }
  },
);

// 初始化
onMounted(() => {
  // TODO: 从后端获取消息列表
});
</script>

<style lang="scss" scoped>
.messages-page {
  .messages-tabs {
    :deep(.el-tabs__header) {
      @apply mb-0;
      margin-right: 1rem;
    }

    :deep(.el-tabs__nav-wrap) {
      &::after {
        display: none;
      }
    }

    :deep(.el-tabs__nav) {
      border: none;
    }

    :deep(.el-tabs__item) {
      @apply px-4 py-2;

      &.is-active {
        @apply text-primary-500 font-medium;
      }
    }
  }

  .messages-list {
    @apply px-6 py-4;

    :deep(.el-table) {
      @apply rounded-lg overflow-hidden;

      .el-table__header {
        @apply bg-gray-50 dark:bg-gray-800;
      }

      .el-table__row {
        @apply transition-colors duration-200;

        &:hover {
          @apply bg-gray-50 dark:bg-gray-800;
        }

        &.unread {
          @apply bg-primary-50 dark:bg-primary-900/20;
        }
      }
    }
  }

  .pagination {
    @apply flex justify-center py-6 px-6 border-t border-gray-100 dark:border-gray-800;
  }

  // 添加筛选框和搜索框的样式
  .filter-select {
    :deep(.el-select) {
      width: 10rem !important;

      .el-input {
        width: 100% !important;
      }

      .el-input__wrapper {
        width: 100% !important;
      }
    }
  }

  .search-input {
    :deep(.el-input) {
      width: 20rem !important;

      .el-input__wrapper {
        width: 100% !important;
      }
    }
  }
}
</style>
